<template>
  <div class="my-switch">
    <el-switch
        v-model="switchModel" @change="change()" :loading="switchLoading"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
  </div>
</template>
<script>

import {successCode} from "@/api/httpApi/base/http.js";
import {constantStore} from "@/stores/constantStore.js";

export default {
  props: {
    switch: {default: null},
    trueAction: {
      type: Function,
      default: null,
      required: false,
    },
    falseAction: {
      type: Function,
      default: null,
      required: false,
    },
    modelAction: {
      type: Function,
      default: null,
      required: false,
    },
  },
  data() {
    return {
      switchModel: false,
      switchLoading: false,
    }
  },
  mounted() {
    this.init(this.switch);
  },
  watch: {
    "switch": {
      handler(newVal) {
        this.init(newVal);
      }
    }
  },
  methods: {
    init(newVal) {
      if (newVal === 0 || newVal === "0" || newVal === false || newVal === "") {
        this.switchModel = false;
        return
      }
      if (newVal === 1 || newVal === "1" || newVal === true) {
        this.switchModel = true;
        return;
      }
      throw new Error("格式错误，仅支持 数字0 1，字符'0' '1' 和 布尔型");
    },
    change() {
      if (this.modelAction !== null) {
        this.switchLoading = true;
        this.modelAction(this.switchModel).then(res => {
          if (res.code !== successCode) {
            this.switchModel = !this.switchModel
          }
          this.switchLoading = false;
        })
      } else {
        if (this.switchModel) {
          if (this.trueAction !== null) {
            this.switchLoading = true;
            this.trueAction(this.switchModel).then(res => {
              if (res.code !== successCode) {
                this.switchModel = false
              }
              this.switchLoading = false;
            })
          }
        } else {
          if (this.falseAction !== null) {
            this.switchLoading = true;
            this.falseAction(this.switchModel).then(res => {
              if (res.code !== successCode) {
                this.switchModel = true
              }
              this.switchLoading = false;
            })
          }
        }
      }

    }
  }
}
</script>

<style scoped lang="scss">
.my-switch {
  user-select: none;
}
</style>